package com.al.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Login {
	public static void main(String[] args) {
		try {
			//加载驱动（用的是反射机制）
			Class.forName("com.mysql.cj.jdbc.Driver");
			//获取连接 (后面的useUnicode=true&characterEncoding=UTF-8参数是为了防止中文乱码,多个参数用&连接)
			//不写参数serverTimezone=UTC会报错，不知道为什么
			String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8";
			String user = "root";
			String password = "";
			Connection connection = DriverManager.getConnection(url, user, password);
			//定义sql语句
			String userName = "小喵";
			//String userId = "7878 or '1' = '1'";  //这个就是 SQL 注入
			String userId = "1";
			/*
			String sql = "select * from users where u_id="+userId+" and u_name='"+userName+"'";
			Statement statement = connection.createStatement();
			ResultSet resultSet = statement.executeQuery(sql);
			*/
			
			//用 PreparedStatement 可以使用占位符
			String sql = "select * from users where u_id = ? and u_name = ?";
			//使用PreparedStatement就不是直接拼接字符串，而是把userId直接拿过去对比，所以就能避免SQL注入
			PreparedStatement preparedStatement = connection.prepareStatement(sql);
			//这里的下标表示的是第一个问号还是第二个问号
			preparedStatement.setString(1, userId);
			preparedStatement.setString(2, userName);
			ResultSet resultSet = preparedStatement.executeQuery();
			if(resultSet.next()) {
				//有此用户，登录成功
				System.out.println("登录成功！");
			} else {
				System.out.println("登录失败！");
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch(SQLException e) {
			e.printStackTrace();
		}
	}
}
